package chapter10.section5;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class PathDemo {
    public static void main(String[] args) throws IOException {
        // 1. 创建Path对象（Paths.get()或Path.of()）
        Path path = Paths.get("demo.txt"); // 等价于 Path.of("demo.txt")
        System.out.println("Path对象: " + path);

        // 2. 获取路径详细信息
        System.out.println("\n路径解析:");
        System.out.println("文件名: " + path.getFileName());
        System.out.println("父目录: " + path.getParent());
        System.out.println("绝对路径: " + path.toAbsolutePath());
        System.out.println("是否为绝对路径: " + path.isAbsolute());

        // 3. 路径组合（resolve）
        Path dir = Paths.get("my_dir");
        Path fileInDir = dir.resolve("data.txt");
        System.out.println("\n组合路径: " + fileInDir);

        // 4. 文件/目录检查
        System.out.println("\n文件检查:");
        System.out.println("是否存在: " + Files.exists(path));
        System.out.println("是否可读: " + Files.isReadable(path));
        System.out.println("是否目录: " + Files.isDirectory(path));

        // 5. 创建文件/目录（演示前先删除可能存在的旧文件）
        Files.deleteIfExists(path);
        Files.createFile(path);
        System.out.println("\n文件创建成功: " + Files.exists(path));

        // 6. 遍历目录（需先创建测试目录）
        Files.createDirectories(dir); // 创建多级目录
        Files.createFile(dir.resolve("file1.txt"));
        Files.createFile(dir.resolve("file2.log"));

        Path file1 = dir.resolve("file1.txt");
        Files.write(file1, "Hello, Java Course".getBytes());
        System.out.println("\n写入内容到file1.txt完成");

        // 7. 文件属性（大小、类型）
        System.out.println("\n文件属性:");
        System.out.println("大小: " + Files.size(path) + " bytes");
        System.out.println("MIME类型: " + Files.probeContentType(path));

        // 清理（删除测试文件和目录）
        Files.delete(path);
        Files.delete(dir.resolve("file1.txt"));
        Files.delete(dir.resolve("file2.log"));
        Files.delete(dir);
    }
}

